package com.iteaj.iot.client.codec;

import com.iteaj.iot.SocketMessage;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.codec.adapter.FixedLengthFrameDecoderAdapter;
import com.iteaj.iot.codec.adapter.LineBasedFrameMessageDecoderAdapter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;

public class LineBaseFrameClient extends TcpSocketClient {

    private int maxLength;
    private boolean failFast;
    private boolean stripDelimiter;

    public LineBaseFrameClient(ClientComponent clientComponent, ClientConnectProperties config, int maxLength) {
        this(clientComponent, config, maxLength, false, true);
    }

    public LineBaseFrameClient(ClientComponent clientComponent, ClientConnectProperties config
            , int maxLength, boolean failFast, boolean stripDelimiter) {
        super(clientComponent, config);
        this.failFast = failFast;
        this.maxLength = maxLength;
        this.stripDelimiter = stripDelimiter;
    }

    @Override
    protected ChannelInboundHandler createProtocolDecoder() {
        return new LineBasedFrameMessageDecoderAdapter(this.maxLength, stripDelimiter, failFast) {

            @Override
            public Class<? extends SocketMessage> getMessageClass() {
                return LineBaseFrameClient.this.getClientComponent().getMessageClass();
            }

            @Override
            public SocketMessage proxy(ChannelHandlerContext ctx, ByteBuf decode) throws Exception {
                return LineBaseFrameClient.this.getClientComponent().proxy(ctx, decode);
            }

            @Override
            public SocketMessage doDecode(ChannelHandlerContext ctx, ByteBuf decode) {
                return LineBaseFrameClient.this.getClientComponent().doDecode(ctx, decode);
            }

            @Override
            public SocketMessage createMessage(byte[] message) {
                return LineBaseFrameClient.this.getClientComponent().createMessage(message);
            }
        };
    }

    public int getMaxLength() {
        return maxLength;
    }

    public boolean isFailFast() {
        return failFast;
    }

    public boolean isStripDelimiter() {
        return stripDelimiter;
    }
}
